#!/bin/bash
# Script to fix cdwork installation

echo "🔧 Fixing cdwork installation..."

# Remove old Python cdwork command if it exists
OLD_CDWORK="/home/linden/.local/bin/cdwork"
if [[ -f "$OLD_CDWORK" ]]; then
    echo "🗑️  Removing old Python cdwork command..."
    rm -f "$OLD_CDWORK" 2>/dev/null || {
        echo "❌ Could not remove $OLD_CDWORK - you may need to run with sudo or manual removal"
        echo "   Try: rm $OLD_CDWORK"
    }
fi

# Get the directory of this script
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CDWORK_SCRIPT="$SCRIPT_DIR/cdwork.sh"

# Detect shell
if [[ -n "$ZSH_VERSION" ]]; then
    SHELL_RC="$HOME/.zshrc"
    SHELL_NAME="zsh"
elif [[ -n "$BASH_VERSION" ]]; then
    SHELL_RC="$HOME/.bashrc"
    SHELL_NAME="bash"
else
    echo "❌ Unsupported shell. Please manually add to your shell configuration:"
    echo "   source '$CDWORK_SCRIPT'"
    exit 1
fi

# Remove old cdwork source lines
if [[ -f "$SHELL_RC" ]]; then
    echo "🧹 Removing old cdwork entries from $SHELL_RC..."
    sed -i.bak '/# cdwork shell function/d; /source.*cdwork\.sh/d' "$SHELL_RC" 2>/dev/null
fi

# Add new cdwork source line
echo "📦 Installing new cdwork shell function..."
echo "" >> "$SHELL_RC"
echo "# cdwork shell function for Claude Code directory navigation" >> "$SHELL_RC"
echo "source '$CDWORK_SCRIPT'" >> "$SHELL_RC"

echo "✅ cdwork shell function installed!"
echo ""
echo "🚀 To use immediately, run one of:"
echo "   source $SHELL_RC"
echo "   source '$CDWORK_SCRIPT'"
echo ""
echo "📋 Usage examples:"
echo "   cdwork           # List directories"
echo "   cdwork -e 1      # Enter directory #1"
echo "   cdwork -v        # Verbose listing"